package action;

import java.io.IOException;
import java.security.interfaces.RSAPrivateKey;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import entity.User;
import util.RSAUtils;

@WebServlet("/Login.action")
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public Login() {
		super();
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String account = request.getParameter("userName");
		String password = request.getParameter("password");
		RSAPrivateKey privateKey = (RSAPrivateKey) request.getSession().getAttribute("privateKey");
		if (privateKey != null) {
			try {
				password = RSAUtils.decryptByPrivateKey(password, privateKey);
			} catch (Exception e) {
				e.printStackTrace();
			}
			request.getSession().removeAttribute("privateKey");
		}
		User user = null;
		if (account.equals("admin") && password.equals("123qwe")) {
			user = new User(account, password);
		}
		if (user != null) {
			request.getSession().setAttribute("user", user);
			response.sendRedirect("index.jsp");
		} else {
			response.sendRedirect("login.jsp");
		}
	}

}
